<?php

namespace App\Policies;

use App\Models\User;
use App\Models\Group;
use Illuminate\Auth\Access\HandlesAuthorization;
use App\Repositories\GroupRepository;

class GroupPolicy
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * @param User $user
     * @param Group $group
     * @return bool
     */
    public function update(User $user, Group $group)
    {
        return $user->id === $group->user_id;
    }

    /**
     * 是否可以创建竞猜
     *
     * @param User $user
     * @param Group $group
     * @return bool
     */
    public function createQuiz(User $user, Group $group)
    {
        /** @var GroupRepository $groupRepository */
        $groupRepository = resolve(GroupRepository::class);
        return $groupRepository->canCreateQuiz($group, $user);
    }

    /**
     * 是否可以删除俱乐部成员
     *
     * @param User $user
     * @param Group $group
     * @return bool
     */
    public function removeUser(User $user, Group $group)
    {
        if ($user->id != $group->user_id) {
            $this->deny('you can\'t remove user');
        }
        if (in_array($user->id, request()->input('users'))) {
            $this->deny('you can\'t remove yourself');
        }
        return true;
    }

    /**
     * 是否可以加入俱乐部
     *
     * @param User $user
     * @param Group $group
     */
    public function join(User $user, Group $group)
    {
        switch (GroupRepository::getAccountStatus($group, $user)) {
            case GroupRepository::GROUP_USER_STATUS_UNAVAILABLE:
                $this->deny('you have been removed');
                break;
            case GroupRepository::GROUP_USER_STATUS_JOINED:
                $this->deny('you have joined the group');
                break;
        }
        if ($group->join_type == GroupRepository::JOINTYPE_CLOSE) {
            $this->deny('can\'t join the club');
        } elseif ($group->join_type == GroupRepository::JOINTYPE_PASSWORD) {
            if (request()->input('password') != $group->join_password) {
                $this->deny('password error');
            }
        }
        return true;
    }
}
